#include <iostream>
#include <string>
#include <vector>

#include <cstdlib>
#include <cassert>
#include <cstdio>
#include <cstring>

#include <pthread.h>
#include <unistd.h>

// 添加__therad,将一个内置类型设置为线程局部存储
// 即变量是全局变量，但是编译的时候每一个线程都有这个变量且不会相互影响
__thread int g_val = 100;

std::string changeId(const pthread_t &thread_id)
{
    char tid[128];
    snprintf(tid, sizeof(tid), "0x%x", thread_id);
    return tid;
}

void *start_routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    // pthread_detach(pthread_self()); // 线程将自己设置为分离

    int cnt = 5;
    while (true)
    {
        std::cout << name << " is running! " << changeId(pthread_self()) << " g_val:" << g_val++ << std::endl;
        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, start_routine, (void *)"thread 1");
    pthread_detach(tid); // 主线程创建后去分离新线程
    std::string maintid = changeId(pthread_self());

    // 一个线程默认是joinable的，如果设置了分离，不会等待线程
    // int n = pthread_join(tid, NULL);
    // std::cout << "result " << n << ":" << strerror(n) << std::endl;

    while (true)
    {
        std::cout << "maintid:" << maintid << " newthread tid:" << changeId(tid) << " g_val:" << g_val << std::endl;
        sleep(1);
    }
    return 0;
}